

package com.platform.common.serializer.json;

import cn.hutool.core.util.StrUtil;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.platform.common.core.oss.baen.ALiOSSStorage;
import com.platform.common.core.oss.baen.LocalStorage;
import com.platform.common.core.oss.baen.Qiniu;
import com.platform.common.config.PlatformBasicConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

@Component
public class ImgJsonSerializer extends JsonSerializer<String> {

    @Resource
    private HttpServletRequest request;

    @Autowired
    private Qiniu qiniu;

    @Autowired
    private ALiOSSStorage aLiOSSStorage;

    @Autowired
    private LocalStorage localStorage;

    @Autowired
    private PlatformBasicConfig shopBasicConfig;

    @Override
    public void serialize(String value, JsonGenerator gen, SerializerProvider serializers) throws IOException {
        if (StrUtil.isBlank(value)) {
            gen.writeString(StrUtil.EMPTY);
            return;
        }
        String[] imgs = value.split(StrUtil.COMMA);
        StringBuilder sb = new StringBuilder();
        String resourcesUrl = localStorage.getResourcesUrlAdmin();

        switch (shopBasicConfig.getStorageType()) {
            case 0:
                resourcesUrl = request.getContextPath().indexOf("/api") != -1 ? localStorage.getResourcesUrlApi() : localStorage.getResourcesUrlAdmin();
                break;
            case 1:
                resourcesUrl = qiniu.getResourcesUrl();
                break;
            case 2:
                resourcesUrl = aLiOSSStorage.getResourcesUrl();
                break;
            default:
        }
        for (String img : imgs) {
            sb.append(resourcesUrl).append(img).append(StrUtil.COMMA);
        }
        sb.deleteCharAt(sb.length() - 1);
        gen.writeString(sb.toString());
    }
}
